package com.fs.utils;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.Toast;

import com.example.studentmanagersystem.URL;
import com.fs.po.Classes;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;



/**
 * 从服务器中获取数据
 * @author chenwenfei
 *
 */
public class GetDataHttpUtil {
	
	private String action;
	private Context context;
	private List<Classes> classList;
	
	public GetDataHttpUtil(Context context) {
		this.context=context;

	}
	
	/**
	 * 获取数据，包括获取用户，获取课程
	 */
	private void getData(String action) {
		this.action=action;
		RequestParams params = new RequestParams();
		params.addBodyParameter("action", action);
		System.out.println("ffffffffffff");
		HttpUtils httpUtils=new HttpUtils();
		httpUtils.send(HttpMethod.POST, URL.ADMIN_URL, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

//				System.out.println("获取到的学生JSON:"+responseInfo.result);
				String jsonString=responseInfo.result;
				
				setStuData(jsonString);
//				Toast.makeText(context, "json"+jsonString, Toast.LENGTH_LONG).show();//【测试】
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				
			}

		});
	}
	
	
		private Classes setStuData(String jsonString) {
				
			Classes cla=null;
				if(jsonString!=null){
					
					try {
						JSONObject jsonObject = new JSONObject(jsonString);
						JSONArray array=jsonObject.getJSONArray("stu");
						for(int i=0;i<array.length();i++){
							JSONObject json=array.getJSONObject(i);
							int class_id=Integer.parseInt(json.getString("_id"));
							String class_name=json.getString("class_name");
							cla=new Classes(class_id, class_name);
							classList.add(cla);
							
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					
				}
//				Toast.makeText(context, "STU"+cla, 0).show();//【测试】
				return cla;
			}

}
